/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package restauranteaplicacion.Ingresos;

import CapaNegocios.CNBebidas;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import entidad.Mesa;
import entidad.Usuarios;
import CapaNegocios.CNMesas;
import CapaNegocios.CNClasificacion;
import CapaNegocios.CNOrden;
import entidad.Clasificacion;
import java.awt.GridLayout;
import java.awt.Image;
import entidad.Platos;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import CapaNegocios.CNPlatos;
import Clases.Observador;
import Clases.OrdenesMesas;
import java.awt.Color;
import java.awt.Component;
import java.util.Observable;
import java.util.Observer;
import restauranteaplicacion.MDI;
import CapaNegocios.CNUsuarios;
import entidad.Bebidas;
import entidad.Detalleorden;
import entidad.Orden;
import java.beans.PropertyVetoException;
import java.net.URL;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import controlrestaurante.pmf;

/**
 *
 * @author Victor
 */
public class Comandas extends javax.swing.JInternalFrame implements Observer, Runnable{

    /**
     * Creates new form IngresoEmpleado
     */
    Observador obs;
    DefaultTableModel modelo;
    public static List<OrdenesMesas> listaOrden;
    Thread hilo;
    Mesa mesaActual;
    public Comandas() {
        initComponents();  
        jDateChooser1.setDate(Calendar.getInstance().getTime());
        modelo = (DefaultTableModel) Tabla.getModel();
        listaOrden = new ArrayList<>();
        obs=new Observador();
        obs.addObserver(this);
        hilo=new Thread(this);
        hilo.start();
        //aqui se cargan todas las mesas;
        cargarMesas();
        cargarInicialOrdenes();//cargar las ordenes que esten en true y sin pagar
        cargarBotonesImagenes();
        mesaActual=null;
        generarObjetos(1);  
        //Tabla.getColumnModel().getColumn(0).setCellRenderer(new TextArea());
        Tabla.setDefaultRenderer(String.class, new TextArea());
        usuarios1 = CNUsuarios.buscarId(1);
        cargarColores();
        lbNombreEmpleado.setText(usuarios1.getEmpleadoidEmpleado().getNombre()+" "+
                usuarios1.getEmpleadoidEmpleado().getApellido());
        
    }
    
    private void cargarInicialOrdenes(){
        //no se estan tomand en cuenta los no pagados solo los que estan activos
        List<Orden> temp= CNOrden.buscarPagados();
        for(Orden or: temp)
        {
            int  x =or.getMesaidMesa().getIdMesa();
            OrdenesMesas tem = OrdenesMesas.buscarOrden(listaOrden, x);
            if(tem!=null)
            {
                tem.setOrden(or);
                tem.setUsuario(or.getUsuarioidUsuario());
                tem.setActivo(true);
                tem.agregarDetalle((List<Detalleorden>) or.getDetalleordenCollection());
            }
        }
        
    }
    
    private void cargarMesas()
    {
        List<Mesa> lista = CNMesas.buscarTodos();
        Iterator<Mesa> itera = lista.listIterator();
        int x = lista.size();
        x = x / 3;
        jPanel8.setLayout(new GridLayout(3,x));
        jPanel8.setSize(248, lista.size()* 75);
        Mesa mes= null;
        x=0;
        while(itera.hasNext())
        {
            mes=itera.next();
             JButton jb = new JButton();
             jb.addActionListener(new ActionListener(){
                 @Override
                 public void actionPerformed(ActionEvent e) {
                     //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                     JButton bAux = (JButton) e.getSource();
                     operarBoton(bAux);                     
                 }
             });
             //jb.setBounds(new Rectangle(50,50,100,75));
             jb.setIcon(ajustarImagen(getClass().getResource("/Images/mesar.png")));
             jb.setText("Mesa "+ String.valueOf(mes.getNumeroMesa()));
             //jb.setIconTextGap(2);
             jb.setHorizontalTextPosition(SwingConstants.CENTER);
             jb.setBackground(Color.WHITE);
             jb.setVerticalTextPosition(SwingConstants.BOTTOM);
             jPanel8.add(jb);
             jb.setName(mes.getIdMesa().toString());
              listaOrden.add(new OrdenesMesas(mes,x));
              x++;
        }
        
    }
    
    private void cargarBotonesImagenes()
    {
        btBebidas.setIcon(ajustarImagen(getClass().getResource("/Images/bebidas.png")));
        btBebidas.setHorizontalTextPosition(SwingConstants.CENTER);
        btBebidas.setVerticalTextPosition(SwingConstants.BOTTOM);
        
        btLicores.setIcon(ajustarImagen(getClass().getResource("/Images/bebidas.png")));
        btLicores.setHorizontalTextPosition(SwingConstants.CENTER);
        btLicores.setVerticalTextPosition(SwingConstants.BOTTOM);
        
        btAntojitos.setIcon(ajustarImagen(getClass().getResource("/Images/Anto.png")));
        btAntojitos.setHorizontalTextPosition(SwingConstants.CENTER);
        btAntojitos.setVerticalTextPosition(SwingConstants.BOTTOM);
        
        btCaldos.setIcon(ajustarImagen(getClass().getResource("/Images/caldos.png")));
        btCaldos.setHorizontalTextPosition(SwingConstants.CENTER);
        btCaldos.setVerticalTextPosition(SwingConstants.BOTTOM);
        
        btCarne.setIcon(ajustarImagen(getClass().getResource("/Images/pollo.png")));
        btCarne.setHorizontalTextPosition(SwingConstants.CENTER);
        btCarne.setVerticalTextPosition(SwingConstants.BOTTOM);
        
        btMariscos.setIcon(ajustarImagen(getClass().getResource("/Images/mar.png")));
        btMariscos.setHorizontalTextPosition(SwingConstants.CENTER);
        btMariscos.setVerticalTextPosition(SwingConstants.BOTTOM);
        
        btPostres.setIcon(ajustarImagen(getClass().getResource("/Images/helado.png")));
        btPostres.setHorizontalTextPosition(SwingConstants.CENTER);
        btPostres.setVerticalTextPosition(SwingConstants.BOTTOM);
        
        btRojas.setIcon(ajustarImagen(getClass().getResource("/Images/carne.png")));
        btRojas.setHorizontalTextPosition(SwingConstants.CENTER);
        btRojas.setVerticalTextPosition(SwingConstants.BOTTOM);  
        
        btDesayunos.setIcon(ajustarImagen(getClass().getResource("/Images/desayuno.png")));
        btDesayunos.setHorizontalTextPosition(SwingConstants.CENTER);
        btDesayunos.setVerticalTextPosition(SwingConstants.BOTTOM); 
    }
    
    private ImageIcon ajustarImagen(URL ico)
    {
        ImageIcon tmpIconAux = new ImageIcon(ico);
        ImageIcon tmpIcon = new ImageIcon(tmpIconAux.getImage().getScaledInstance(40, 40, Image.SCALE_DEFAULT));
        return tmpIcon;
    }
    
    private void operarBoton(JButton boton)
    {
        mesaActual = CNMesas.buscarId(Integer.parseInt(boton.getName()));
        jTabbedPane1.setTitleAt(1, "Orden de "+boton.getText());
        jTabbedPane1.setSelectedIndex(jTabbedPane1.indexOfComponent(jScrollPane2));
        OrdenesMesas orden = OrdenesMesas.buscarOrden(listaOrden, mesaActual.getIdMesa());       
        clearTable();
        if(orden.isActivo())
        {
            orden.regresarModelo(modelo);
            Float total =orden.total();
            lbSubtotal.setText(total.toString());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        usuarios1 = new entidad.Usuarios();
        jPanel1 = new javax.swing.JPanel();
        lbNombreEmpleado = new javax.swing.JLabel();
        jDateChooser1 = new com.toedter.calendar.JDateChooser();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        jPanel8 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        Tabla = new javax.swing.JTable();
        jPanel7 = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        lbSubtotal = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        jPanel10 = new javax.swing.JPanel();
        jPanel11 = new javax.swing.JPanel();
        renviarCocina = new javax.swing.JButton();
        jPanel12 = new javax.swing.JPanel();
        btnPagar = new javax.swing.JButton();
        btnEnviar = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        btCaldos = new javax.swing.JButton();
        btRojas = new javax.swing.JButton();
        btPostres = new javax.swing.JButton();
        btAntojitos = new javax.swing.JButton();
        btBebidas = new javax.swing.JButton();
        btLicores = new javax.swing.JButton();
        btCarne = new javax.swing.JButton();
        btMariscos = new javax.swing.JButton();
        btDesayunos = new javax.swing.JButton();
        panelMenu = new javax.swing.JPanel();

        setBackground(new java.awt.Color(255, 255, 255));
        setClosable(true);
        setIconifiable(true);
        setTitle("Creacion Meseros");
        setAutoscrolls(true);
        setMaximumSize(new java.awt.Dimension(1224, 720));
        setMinimumSize(new java.awt.Dimension(800, 650));
        setPreferredSize(new java.awt.Dimension(1224, 720));
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));

        jPanel1.setBackground(new java.awt.Color(54, 149, 240));
        jPanel1.setAutoscrolls(true);
        jPanel1.setMaximumSize(new java.awt.Dimension(2000, 50));
        jPanel1.setMinimumSize(new java.awt.Dimension(246, 50));
        jPanel1.setPreferredSize(new java.awt.Dimension(1024, 50));
        jPanel1.setLayout(null);

        lbNombreEmpleado.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        lbNombreEmpleado.setForeground(new java.awt.Color(255, 255, 255));

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, usuarios1, org.jdesktop.beansbinding.ELProperty.create("${userName}"), lbNombreEmpleado, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jPanel1.add(lbNombreEmpleado);
        lbNombreEmpleado.setBounds(70, 10, 300, 20);
        jPanel1.add(jDateChooser1);
        jDateChooser1.setBounds(970, 10, 230, 30);

        jLabel5.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(255, 255, 255));
        jLabel5.setText("Comandas");
        jPanel1.add(jLabel5);
        jLabel5.setBounds(420, 10, 360, 29);

        jLabel6.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel6.setForeground(new java.awt.Color(255, 255, 255));
        jLabel6.setText("Usuario");
        jPanel1.add(jLabel6);
        jLabel6.setBounds(20, 10, 60, 20);

        getContentPane().add(jPanel1);

        jPanel4.setPreferredSize(new java.awt.Dimension(1024, 550));
        jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 2));

        jPanel5.setPreferredSize(new java.awt.Dimension(250, 640));
        jPanel5.setLayout(new javax.swing.BoxLayout(jPanel5, javax.swing.BoxLayout.Y_AXIS));

        jTabbedPane1.setToolTipText("Mesa\nOrden");
        jTabbedPane1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTabbedPane1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 248, Short.MAX_VALUE)
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 520, Short.MAX_VALUE)
        );

        jScrollPane3.setViewportView(jPanel8);

        jTabbedPane1.addTab("Mesas", jScrollPane3);

        Tabla.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        Tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre", "Cantidad", "Precio", "<html>Nota</html>"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Float.class, java.lang.Float.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        Tabla.setColumnSelectionAllowed(true);
        Tabla.setGridColor(new java.awt.Color(255, 255, 255));
        Tabla.getTableHeader().setReorderingAllowed(false);
        Tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TablaMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(Tabla);
        Tabla.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        Tabla.getColumnModel().getColumn(0).setMinWidth(60);
        Tabla.getColumnModel().getColumn(0).setPreferredWidth(60);
        Tabla.getColumnModel().getColumn(0).setMaxWidth(60);
        Tabla.getColumnModel().getColumn(1).setMinWidth(70);
        Tabla.getColumnModel().getColumn(1).setPreferredWidth(70);
        Tabla.getColumnModel().getColumn(1).setMaxWidth(70);

        jTabbedPane1.addTab("Orden", jScrollPane2);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE)
        );

        jPanel5.add(jPanel3);

        jPanel7.setMaximumSize(new java.awt.Dimension(250, 275));
        jPanel7.setMinimumSize(new java.awt.Dimension(250, 275));
        jPanel7.setPreferredSize(new java.awt.Dimension(250, 275));

        jPanel9.setMaximumSize(new java.awt.Dimension(250, 80));
        jPanel9.setMinimumSize(new java.awt.Dimension(250, 50));
        jPanel9.setPreferredSize(new java.awt.Dimension(250, 80));

        lbSubtotal.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
        lbSubtotal.setText("0.00");

        jLabel2.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
        jLabel2.setText("Q.");

        jLabel3.setFont(new java.awt.Font("Arial", 1, 16)); // NOI18N
        jLabel3.setText("Total");

        jButton1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restauranteaplicacion/Ingresos/clipboard-3x.png"))); // NOI18N
        jButton1.setText("<html>Cambio Mesa</html>");
        jButton1.setBorder(null);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setMargin(new java.awt.Insets(6, 14, 6, 14));
        jButton1.setPreferredSize(new java.awt.Dimension(70, 23));
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        btnEliminar.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restauranteaplicacion/Ingresos/circle-x-3x.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/restauranteaplicacion/Ingresos/circle-x-3x.png"))); // NOI18N
        btnEliminar.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/restauranteaplicacion/Ingresos/circle-x-3x.png"))); // NOI18N
        btnEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEliminar.setIconTextGap(1);
        btnEliminar.setMargin(new java.awt.Insets(2, 2, 2, 2));
        btnEliminar.setPreferredSize(new java.awt.Dimension(70, 23));
        btnEliminar.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        btnEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel9Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lbSubtotal, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel9Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(btnEliminar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbSubtotal)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 56, Short.MAX_VALUE)
                    .addComponent(btnEliminar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        jPanel7.add(jPanel9);

        jPanel10.setBackground(new java.awt.Color(255, 255, 255));
        jPanel10.setMaximumSize(new java.awt.Dimension(250, 200));
        jPanel10.setMinimumSize(new java.awt.Dimension(250, 200));
        jPanel10.setPreferredSize(new java.awt.Dimension(250, 200));
        jPanel10.setLayout(new java.awt.GridLayout(2, 0));

        jPanel11.setBackground(new java.awt.Color(255, 255, 255));
        jPanel11.setLayout(new java.awt.GridLayout(2, 2, 2, 2));

        renviarCocina.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        renviarCocina.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restauranteaplicacion/Ingresos/monitor-3x.png"))); // NOI18N
        renviarCocina.setText("Reenviar a Cocina");
        renviarCocina.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/restauranteaplicacion/Ingresos/circle-x-3x.png"))); // NOI18N
        renviarCocina.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/restauranteaplicacion/Ingresos/circle-x-3x.png"))); // NOI18N
        renviarCocina.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        renviarCocina.setIconTextGap(1);
        renviarCocina.setMargin(new java.awt.Insets(2, 2, 2, 2));
        renviarCocina.setPreferredSize(new java.awt.Dimension(70, 23));
        renviarCocina.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        renviarCocina.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        renviarCocina.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                renviarCocinaActionPerformed(evt);
            }
        });
        jPanel11.add(renviarCocina);

        jPanel10.add(jPanel11);

        jPanel12.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 5, 25, 5));
        jPanel12.setLayout(new java.awt.GridLayout(1, 1, 10, 10));

        btnPagar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restauranteaplicacion/Ingresos/task-3x.png"))); // NOI18N
        btnPagar.setText("Pagar");
        btnPagar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnPagar.setPreferredSize(new java.awt.Dimension(60, 23));
        btnPagar.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        btnPagar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnPagar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPagarActionPerformed(evt);
            }
        });
        jPanel12.add(btnPagar);

        btnEnviar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restauranteaplicacion/Ingresos/monitor-3x.png"))); // NOI18N
        btnEnviar.setText("Enviar"); // NOI18N
        btnEnviar.setToolTipText("");
        btnEnviar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEnviar.setMargin(new java.awt.Insets(2, 2, 2, 2));
        btnEnviar.setPreferredSize(new java.awt.Dimension(60, 23));
        btnEnviar.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        btnEnviar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEnviarActionPerformed(evt);
            }
        });
        jPanel12.add(btnEnviar);

        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restauranteaplicacion/Ingresos/x-3x.png"))); // NOI18N
        jButton5.setText("Salir");
        jButton5.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton5.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jButton5.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel12.add(jButton5);

        jPanel10.add(jPanel12);

        jPanel7.add(jPanel10);

        jPanel5.add(jPanel7);

        jPanel4.add(jPanel5);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setMaximumSize(new java.awt.Dimension(1024, 650));
        jPanel2.setMinimumSize(new java.awt.Dimension(800, 500));
        jPanel2.setPreferredSize(new java.awt.Dimension(955, 640));
        jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.PAGE_AXIS));

        jPanel6.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
        jPanel6.setAutoscrolls(true);
        jPanel6.setMaximumSize(new java.awt.Dimension(1000, 100));
        jPanel6.setMinimumSize(new java.awt.Dimension(754, 80));
        jPanel6.setPreferredSize(new java.awt.Dimension(955, 100));
        jPanel6.setLayout(new java.awt.GridLayout(1, 1, 10, 20));

        btCaldos.setBackground(new java.awt.Color(255, 255, 255));
        btCaldos.setText("Caldos");
        btCaldos.setBorder(null);
        btCaldos.setMargin(new java.awt.Insets(2, 2, 2, 2));
        btCaldos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCaldosActionPerformed(evt);
            }
        });
        jPanel6.add(btCaldos);

        btRojas.setBackground(new java.awt.Color(255, 255, 255));
        btRojas.setText("<html>Carnes Rojas</html>");
        btRojas.setAlignmentY(0.0F);
        btRojas.setBorder(null);
        btRojas.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btRojas.setIconTextGap(0);
        btRojas.setMargin(new java.awt.Insets(2, 2, 2, 2));
        btRojas.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btRojas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btRojasActionPerformed(evt);
            }
        });
        jPanel6.add(btRojas);

        btPostres.setBackground(new java.awt.Color(255, 255, 255));
        btPostres.setText("Postres");
        btPostres.setBorder(null);
        btPostres.setMargin(new java.awt.Insets(2, 2, 2, 2));
        btPostres.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPostresActionPerformed(evt);
            }
        });
        jPanel6.add(btPostres);

        btAntojitos.setBackground(new java.awt.Color(255, 255, 255));
        btAntojitos.setText("Antojitos");
        btAntojitos.setBorder(null);
        btAntojitos.setMargin(new java.awt.Insets(2, 2, 2, 2));
        btAntojitos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAntojitosActionPerformed(evt);
            }
        });
        jPanel6.add(btAntojitos);

        btBebidas.setBackground(new java.awt.Color(255, 255, 255));
        btBebidas.setText("Bebidas");
        btBebidas.setBorder(null);
        btBebidas.setMargin(new java.awt.Insets(2, 2, 2, 2));
        btBebidas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btBebidasActionPerformed(evt);
            }
        });
        jPanel6.add(btBebidas);

        btLicores.setBackground(new java.awt.Color(255, 255, 255));
        btLicores.setText("Licores");
        btLicores.setBorder(null);
        btLicores.setMargin(new java.awt.Insets(2, 2, 2, 2));
        btLicores.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLicoresActionPerformed(evt);
            }
        });
        jPanel6.add(btLicores);

        btCarne.setBackground(new java.awt.Color(255, 255, 255));
        btCarne.setText("Carne Blanca");
        btCarne.setBorder(null);
        btCarne.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCarneActionPerformed(evt);
            }
        });
        jPanel6.add(btCarne);

        btMariscos.setBackground(new java.awt.Color(255, 255, 255));
        btMariscos.setText("Mariscos");
        btMariscos.setBorder(null);
        btMariscos.setMargin(new java.awt.Insets(2, 2, 2, 2));
        btMariscos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btMariscosActionPerformed(evt);
            }
        });
        jPanel6.add(btMariscos);

        btDesayunos.setBackground(new java.awt.Color(255, 255, 255));
        btDesayunos.setText("Desayunos");
        btDesayunos.setBorder(null);
        btDesayunos.setMargin(new java.awt.Insets(2, 2, 2, 2));
        btDesayunos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDesayunosActionPerformed(evt);
            }
        });
        jPanel6.add(btDesayunos);

        jPanel2.add(jPanel6);

        panelMenu.setBackground(new java.awt.Color(255, 255, 255));
        panelMenu.setAutoscrolls(true);
        panelMenu.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        panelMenu.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
        jPanel2.add(panelMenu);

        jPanel4.add(jPanel2);

        getContentPane().add(jPanel4);

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

        //Agregar los platos y bebidas dinamcos con sus botones
    
    private void generarObjetosBebidas(Clasificacion clas)
    {
        List <Bebidas > lista = CNClasificacion.buscarBebidas(clas);
        Arrays.sort(lista.toArray());
        Iterator<Bebidas> iter = lista.listIterator();
        Bebidas bebida=null;
        //panelMenu.setLayout(new GridLayout());
        while(iter.hasNext())
        {
            bebida=iter.next();
            JButton jb = new JButton();
             jb.addActionListener(new ActionListener(){
                 @Override
                 public void actionPerformed(ActionEvent e) {
                     //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                     JButton buton = (JButton) e.getSource();
                     int id = Integer.parseInt(buton.getName());//e.getActionCommand());
                     if(mesaActual!=null)
                        agregarTablaBebida(id);
                     else
                          JOptionPane.showMessageDialog(buton.getParent(), "No se ha seleccionado una Mesa", "Error", JOptionPane.ERROR_MESSAGE);
                 }
             });
             //Color
            jb.setBackground(new java.awt.Color(255, 255, 255));
            jb.setForeground(new java.awt.Color(102, 102, 255));
            jb.setName(bebida.getIdbebidas().toString());
            //jb.setActionCommand(plato.getIdPlatos().toString());
            jb.setIcon(ajustarImagen(getClass().getResource("/Images/caldo2.png")));
            jb.setText( String.valueOf(bebida.getNombre()));
            jb.setHorizontalTextPosition(SwingConstants.CENTER);
            jb.setVerticalTextPosition(SwingConstants.BOTTOM);
            panelMenu.add(jb);
        }
        panelMenu.updateUI();
    }
    private void generarObjetos(int x)
    {
        panelMenu.removeAll();
        Clasificacion clas = CNClasificacion.buscarId(x);
        if(x==5 || x==9)
        {
            generarObjetosBebidas(clas);
            return;
        }
        List <Platos > lista = CNClasificacion.buscarPlatos(clas);
        Arrays.sort(lista.toArray());
        Iterator<Platos> iter = lista.listIterator();
        Platos plato=null;
        //panelMenu.setLayout(new GridLayout());
        while(iter.hasNext())
        {
            plato=iter.next();
            JButton jb = new JButton();
             jb.addActionListener(new ActionListener(){
                 @Override
                 public void actionPerformed(ActionEvent e) {
                     //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                     JButton buton = (JButton) e.getSource();
                     int id = Integer.parseInt(buton.getName());//e.getActionCommand());
                     if(mesaActual!=null)
                        agregarTabla(id);
                     else
                          JOptionPane.showMessageDialog(buton.getParent(), "No se ha seleccionado una Mesa", "Error", JOptionPane.ERROR_MESSAGE);
                 }
             });
             //Color
            jb.setBackground(new java.awt.Color(255, 255, 255));
            jb.setForeground(new java.awt.Color(102, 102, 255));
            jb.setName(plato.getIdPlatos().toString());
            //jb.setActionCommand(plato.getIdPlatos().toString());
            jb.setIcon(ajustarImagen(getClass().getResource("/Images/caldo2.png")));
            jb.setText( String.valueOf(plato.getNombre()));
            jb.setHorizontalTextPosition(SwingConstants.CENTER);
            jb.setVerticalTextPosition(SwingConstants.BOTTOM);
            panelMenu.add(jb);
        }
        panelMenu.updateUI();
        //jTabbedPane1.setSelectedIndex( jTabbedPane1.getSelectedIndex());
    }
    
    private void agregarTabla(int id)
    {
        Platos plato = CNPlatos.buscarId(id);
        OrdenesMesas orden= OrdenesMesas.buscarOrden(listaOrden, mesaActual.getIdMesa());
        clearTable();
        orden.AgregarPlato(plato);
        orden.regresarModelo(modelo);
        Float hola = Float.valueOf(0);
        hola = hola + orden.total();
        lbSubtotal.setText(hola.toString());
    }
    
    private void agregarTablaBebida(int id)
    {
        Bebidas bebida = CNBebidas.buscarId(id);
        OrdenesMesas orden= OrdenesMesas.buscarOrden(listaOrden, mesaActual.getIdMesa());
        clearTable();
        orden.AgregarBebida(bebida);
        orden.regresarModelo(modelo);
        Float hola = Float.valueOf(0);
        hola = hola + orden.total();
        lbSubtotal.setText(hola.toString());
    }
    
     private void clearTable(){
        for (int i = 0; i < Tabla.getRowCount(); i++) {
            modelo.removeRow(i);
            i-=1;
        }
     }
    private void btRojasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRojasActionPerformed
        // TODO add your handling code here:
        generarObjetos(2);
    }//GEN-LAST:event_btRojasActionPerformed

    private void btCaldosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCaldosActionPerformed
        // TODO add your handling code here:
        generarObjetos(1);
    }//GEN-LAST:event_btCaldosActionPerformed

    private void btPostresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPostresActionPerformed
        // TODO add your handling code here:
        generarObjetos(3);
    }//GEN-LAST:event_btPostresActionPerformed

    private void btAntojitosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAntojitosActionPerformed
        // TODO add your handling code here:
        generarObjetos(4);
    }//GEN-LAST:event_btAntojitosActionPerformed

    private void btBebidasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBebidasActionPerformed
        // TODO add your handling code here:
        generarObjetos(5);
    }//GEN-LAST:event_btBebidasActionPerformed

    private void btCarneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCarneActionPerformed
        // TODO add your handling code here:
        generarObjetos(6);
    }//GEN-LAST:event_btCarneActionPerformed

    private void btMariscosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btMariscosActionPerformed
        // TODO add your handling code here:
        generarObjetos(7);
    }//GEN-LAST:event_btMariscosActionPerformed

    private void regresarPanel()
    {
        cargarColores();
        mesaActual=null;
        jTabbedPane1.setTitleAt(1,"Orden");
        clearTable();
        lbSubtotal.setText("0.0");
    }
    
    private void jTabbedPane1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTabbedPane1MouseClicked
        // TODO add your handling code here:
        if(jTabbedPane1.getModel().getSelectedIndex()==0)
        {
            regresarPanel();
        }
        if(jTabbedPane1.getModel().getSelectedIndex()==1)
        {
            if(mesaActual== null)
            {
                JOptionPane.showMessageDialog(this, "No a seleccionado una mesa", "Error", JOptionPane.ERROR_MESSAGE);
                jTabbedPane1.setSelectedIndex(0);
            }
        }
    }//GEN-LAST:event_jTabbedPane1MouseClicked

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        if(Tabla.getSelectedRow()== -1 || mesaActual==null)
        {
           JOptionPane.showMessageDialog(this, "No se ha seleccionado un elemento", "Error", JOptionPane.ERROR_MESSAGE);                         
        }
        else
        {
            //realizar la selecion del elemento;
            int x = Tabla.getSelectedRow();
            OrdenesMesas orden = OrdenesMesas.buscarOrden(listaOrden, mesaActual.getIdMesa());
            if(orden.getDetalle().get(x).setCantidadDisminuir())
            {
                orden.eliminaDetalle(x);
            }
            clearTable();
            orden.regresarModelo(modelo);
            Float hola = Float.valueOf(0);
            hola = hola + orden.total();
            lbSubtotal.setText(hola.toString());
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
        if(OrdenesMesas.verificarMesasSinOrden(listaOrden))
            this.setVisible(false);
        else
        {
            JOptionPane.showMessageDialog(this, "Hay ordenes sin Guardar, porfavor cancelar todas las ordenes", "Error", JOptionPane.ERROR_MESSAGE); 
        }
    }//GEN-LAST:event_jButton5ActionPerformed
    //Para poder pagar y cancelar la mesa.
    private void btnPagarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPagarActionPerformed
        // TODO add your handling code here:
        if(mesaActual !=null)
        {
            OrdenesMesas orden = OrdenesMesas.buscarOrden(listaOrden, mesaActual.getIdMesa());
            //Parametros.padre = orden;
            //orden.setUsuario(usuarios1);
            if(orden.getOrden()==null)
            {
                Orden orden1 = new Orden();
                orden1.setActivo(true);
                orden1.setDetalleordenCollection(orden.regresarDetalleOrdenes());
                orden1.setMesaidMesa(mesaActual);
                orden1.setUsuarioidUsuario(usuarios1);
                orden1.setFecha(Calendar.getInstance().getTime());
                orden1.setNoOrden(CNOrden.regresarNumeroOrde());
                if(CNOrden.insertar(orden1))
                {
                    orden.setOrden(orden1);
                    orden.agregarDetalle((List<Detalleorden>) orden1.getDetalleordenCollection());
                }
            }
            orden.getOrden().setDetalleordenCollection(orden.regresarDetalleOrdenes());
            int x = listaOrden.indexOf(orden);
            //orden.setUsuario(usuarios1);
            
            IngresoPagos ing = new IngresoPagos(obs,x);
            MDI.getDesktopPane().add(ing);
            ing.setVisible(true);
            this.Desactivar();
            
        }
        else
            JOptionPane.showMessageDialog(this, "No ha seleccionado una Mesa a cancelar", "Error", JOptionPane.ERROR_MESSAGE); 
    }//GEN-LAST:event_btnPagarActionPerformed

    private void TablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TablaMouseClicked
        // TODO add your handling code here:
        int x = Tabla.getSelectedRow();
        if(Tabla.isColumnSelected(3))
        {
            String des = JOptionPane.showInputDialog("Ingresar Nota: ", "");
            if(des!=null)
            {
                OrdenesMesas orden= OrdenesMesas.buscarOrden(listaOrden, mesaActual.getIdMesa());
                clearTable();
                orden.agregarOrdenMesa(x, des);
                orden.regresarModelo(modelo);
            }
        }
    }//GEN-LAST:event_TablaMouseClicked

    private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnviarActionPerformed
        // TODO add your handling code here:
        
        
        if(mesaActual !=null)
        {
            Object[] temp = CNUsuarios.buscarActivos().toArray();
            Object showInputDialog = JOptionPane.showInputDialog(this, "Seleccion el mesero", "Seleccion de mesero", JOptionPane.OK_OPTION, frameIcon, temp, mesaActual);
            Usuarios usuarioTemporal = (Usuarios)showInputDialog;     
            if(usuarioTemporal == null)
                return;
            OrdenesMesas orden = OrdenesMesas.buscarOrden(listaOrden, mesaActual.getIdMesa());
            if(orden.getOrden()==null)
            {
                orden.setUsuario(usuarioTemporal);
                orden.HoraInicial= Calendar.getInstance().getTime().getHours();
                orden.MinutoInicial = Calendar.getInstance().getTime().getMinutes();
                Orden orden1 = new Orden();
                orden1.setActivo(true);
                orden1.setDetalleordenCollection(orden.regresarDetalleOrdenes());
                orden1.setMesaidMesa(mesaActual);
                orden1.setUsuarioidUsuario(usuarioTemporal);
                orden1.setFecha(Calendar.getInstance().getTime());
                orden1.setNoOrden(CNOrden.regresarNumeroOrde());

                if(CNOrden.insertar(orden1))
                {
                    orden.setOrden(orden1);
                    orden.agregarDetalle((List<Detalleorden>) orden1.getDetalleordenCollection());
                     regresarPanel();
                     jTabbedPane1.setSelectedIndex(0);
                }
                else
                    JOptionPane.showMessageDialog(this, "No se puedo enviar la orden :", "Error", 
                        JOptionPane.ERROR_MESSAGE);
            }
            else
            {
                pmf.getInstancia().cerrarEMF();
                orden.getOrden().setDetalleordenCollection(orden.regresarDetalleOrdenes());
                orden.getOrden().setActivo(true);
                if(CNOrden.modificar(orden.getOrden()))
                {
                    orden.agregarDetalle((List<Detalleorden>) orden.getOrden().getDetalleordenCollection());
                     regresarPanel();
                     jTabbedPane1.setSelectedIndex(0);
                }
            }
        }
        else
            JOptionPane.showMessageDialog(this, "No ha seleccionado una Mesa para enviar parametros", "Error", JOptionPane.ERROR_MESSAGE); 
    }//GEN-LAST:event_btnEnviarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        if(mesaActual== null)
            JOptionPane.showMessageDialog(this, "No a seleccionado una mesa", "Error", JOptionPane.ERROR_MESSAGE);
        else {
            Object[] temp = CNMesas.buscarTodos().toArray();
            Object showInputDialog = JOptionPane.showInputDialog(this, "Seleccion la mesa Actual", "Seleccion de MEsa", JOptionPane.OK_OPTION, frameIcon, temp, mesaActual);
            Mesa mes = (Mesa)showInputDialog;
            if(mes==null)
                return ;
            OrdenesMesas ordenActual = OrdenesMesas.buscarOrden(listaOrden, mesaActual.getIdMesa());
            if(ordenActual.getOrden()!=null)
                return ;            
            OrdenesMesas ordenDespues = OrdenesMesas.buscarOrden(listaOrden, mes.getIdMesa());
            if(ordenDespues.getOrden()!=null)
                return ;
            if(ordenDespues.isActivo())
                JOptionPane.showMessageDialog(this, "La mesa ya esta ocupada", "Error", JOptionPane.ERROR_MESSAGE);
            else
            {
                ordenDespues.setDetalle(ordenActual.getDetalle());
                ordenActual.eliminarDetalle();
            }
            cargarColores();
            mesaActual=null;
            jTabbedPane1.setTitleAt(1,"Orden");
            clearTable();
            lbSubtotal.setText("0.0");
            jTabbedPane1.setSelectedIndex(0);
        }
        
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btDesayunosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDesayunosActionPerformed
        // TODO add your handling code here:
        generarObjetos(8);
    }//GEN-LAST:event_btDesayunosActionPerformed

    private void renviarCocinaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renviarCocinaActionPerformed
        // TODO add your handling code here:
        if(mesaActual== null)
        {
            JOptionPane.showMessageDialog(this, "No a seleccionado una mesa", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int fila = JOptionPane.showInternalConfirmDialog(this, "Desea Reevniar toda la orden "
                + " a cocina", "Confirmacion",1, 0);
        if(fila == JOptionPane.OK_OPTION)
        { 
            OrdenesMesas orden = OrdenesMesas.buscarOrden(listaOrden, mesaActual.getIdMesa());
            orden.getOrden().setDetalleordenCollection(orden.regresarDetalleOrdenes());
            orden.getOrden().setActivo(true);
            if(CNOrden.modificar(orden.getOrden()))
            {
                CNOrden.entradaCocina(orden.getOrden().getIdOrden());
                orden.agregarDetalle((List<Detalleorden>) orden.getOrden().getDetalleordenCollection());
                 regresarPanel();
                 jTabbedPane1.setSelectedIndex(0);
            }
        }
    }//GEN-LAST:event_renviarCocinaActionPerformed

    private void btLicoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLicoresActionPerformed
        // TODO add your handling code here:
        generarObjetos(9);
    }//GEN-LAST:event_btLicoresActionPerformed

    private void cargarColores()
    {
        Iterator<OrdenesMesas> iter = listaOrden.listIterator();
        OrdenesMesas orden = null;
        while(iter.hasNext())
        {
            orden = iter.next();
            JButton boton = (JButton) jPanel8.getComponent(orden.getIndexBoton());
            if(orden.isActivo())                
                boton.setIcon(ajustarImagen(getClass().getResource("/Images/mesav.png")));
            else
            {
                orden.reiniciar();
                boton.setIcon(ajustarImagen(getClass().getResource("/Images/mesar.png")));
            }
        }
    }
    
   
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable Tabla;
    private javax.swing.JButton btAntojitos;
    private javax.swing.JButton btBebidas;
    private javax.swing.JButton btCaldos;
    private javax.swing.JButton btCarne;
    private javax.swing.JButton btDesayunos;
    private javax.swing.JButton btLicores;
    private javax.swing.JButton btMariscos;
    private javax.swing.JButton btPostres;
    private javax.swing.JButton btRojas;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnEnviar;
    private javax.swing.JButton btnPagar;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton5;
    private com.toedter.calendar.JDateChooser jDateChooser1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel lbNombreEmpleado;
    private javax.swing.JLabel lbSubtotal;
    private javax.swing.JPanel panelMenu;
    private javax.swing.JButton renviarCocina;
    private entidad.Usuarios usuarios1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    private void Desactivar()
    {
        for(Component x :this.jPanel1.getComponents())
        {
            x.setEnabled(false);
        }
        for(Component x :this.jPanel4.getComponents())
        {
            x.setEnabled(false);
        }
    }
    
    private void Activar()
    {
        for(Component x :this.jPanel1.getComponents())
        {
            x.setEnabled(true);
        }
        for(Component x :this.jPanel4.getComponents())
        {
            x.setEnabled(true);
        }
        
    }
    
    @Override
    public void update(Observable o, Object arg) {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        Activar();        
            mesaActual=null;
            jTabbedPane1.setTitleAt(1,"Orden");
            clearTable();
            lbSubtotal.setText("0.0");
            cargarColores();
            jTabbedPane1.setSelectedIndex(jTabbedPane1.indexOfComponent(jScrollPane3));
            
    }

    @Override
    public void run() {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        Thread ct = Thread.currentThread();
        while(ct==hilo)
        {
            try {
                 List<Orden> temp= CNOrden.buscarPagados();
                 boolean cambios = false;
                 for(OrdenesMesas ordenMesa: listaOrden)
                 {
                     if(ordenMesa.isActivo())
                     {
                        boolean bandera = true;
                        for(Orden comanda : temp)
                        {
                            if(ordenMesa.getOrden()!=null)
                               if(ordenMesa.getOrden().equals(comanda))
                               {
                                   bandera = false;
                                   temp.remove(comanda);
                                   break;
                               }
                        }
                        if(bandera && ordenMesa.getOrden()!=null )
                        {
                            cambios = true;
                            ordenMesa.reiniciar();
                        }
                     }
                 }
                 if(!temp.isEmpty())
                     for(Orden temporal : temp)
                     {
                         int  x =temporal.getMesaidMesa().getIdMesa();
                        OrdenesMesas tem = OrdenesMesas.buscarOrden(listaOrden, x);
                        if(tem!=null)
                        {
                            tem.setOrden(temporal);
                            tem.setUsuario(temporal.getUsuarioidUsuario());
                            tem.setActivo(true);
                            tem.agregarDetalle((List<Detalleorden>) temporal.getDetalleordenCollection());
                        }
                         cambios = true;
                     }
                 if(cambios)
                 {
                     cargarColores();
                 }
               
            }
             catch(Exception e){
                  System.out.println(e.toString());
             };
             try{
              hilo.sleep( 6000 );
             }
             catch(Exception e){System.out.println(e.toString());};
        }
    }
}
